package com.briup.authentication.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

/**
 * 资源服务器配置
 */
@Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 设置校验token端点
     * @return
     */
    @Bean
    @Primary
    public RemoteTokenServices remoteTokenServices() {
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        // 设置资源服务器check_token端点完整地址
        // 注意 校验 access_token地址必须为 /oauth/check_token
        remoteTokenServices.setCheckTokenEndpointUrl("http://127.0.0.1:9999/oauth/check_token");
        // 设置 客户端编号，与授权服务器编号保持一致
        // 注意: 这里要从数据库查询出来，这里我只是为了方便测试
        remoteTokenServices.setClientId("briup_oauth");
        remoteTokenServices.setClientSecret("briup_secret");
        return remoteTokenServices;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 设置session策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);

        //  任何请求都需要校验
        http.authorizeRequests().anyRequest().authenticated();

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 设置校验token令牌服务
        resources.tokenServices(remoteTokenServices());
        // 设置资源id
        resources.resourceId("briup_resource");
    }
}
